package com.anjingsi.tools.resttemplate;

import com.anjingsi.tools.Result;
import com.google.gson.Gson;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.ResponseErrorHandler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * restTemplate中的ErrorHandler异常处理
 * @author anjingsi
 */
public class FaceResponseErrorHandler implements ResponseErrorHandler {

    /** 对response进行判断，如果是异常情况，返回true */
    @Override
    public boolean hasError(ClientHttpResponse response) throws IOException {
        if(response.getStatusCode().value() == 200){
            System.out.println("接口调用返回的状态值为200");
            String result = convertStreamToString(response.getBody());
            Result jsonResponse = new Gson().fromJson(result,Result.class);
            if(jsonResponse.getCode() != 200){
                System.out.println("接口调用返回的状态值不为200");
                return true;
            }
            return false;
        }
        System.out.println("接口调用返回的状态值为："+ response.getStatusCode().value()+"   当前接口请求有问题");
        return true;
    }

    /**
     * 异常情况时的处理方法
     * @param response
     */
    @Override
    public void handleError(ClientHttpResponse response) throws IOException {
        throw new RuntimeException("出现异常了" + response.getBody().toString());
    }

    /**
     * InputStream转成String
     * @param is InputStream
     * @return String
     */
    private String convertStreamToString(InputStream is) throws IOException {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException("出现异常了");
        } finally {
            is.close();
        }

        return sb.toString();
    }
}
